<?php
session_start();
$host = 'localhost';
$dbname = 'your_db';
$username = 'your_user';
$password = 'your_pwd';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("数据库连接失败: " . $e->getMessage());
}

function generate_hash_code($username) {
    $salt = 'unique_salt_string';
    $hash = hash('sha256', $username . $salt . time());
    return substr($hash, 0, 6);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nickname = $_POST['nickname'];
    $password = $_POST['password'];
    $email = $_POST['email'];
    $code = generate_hash_code($nickname);
    
    $expire_time = time() + 3600;
    $stmt = $pdo->prepare("
        INSERT INTO users (nickname, password, email, activation_code, expire_time, status)
        VALUES (?, ?, ?, ?, ?, 0)
    ");
    $stmt->execute([$nickname, password_hash($password, PASSWORD_DEFAULT), $email, $code, $expire_time]);
    
    $activation_url = "http://127.0.0.1/verify?user={$nickname}&code={$code}";
    $subject = "会员激活邮件";
    $message = "点击链接激活账号：\n{$activation_url}\n(有效期1小时)";
    $headers = "From: noreply@yourdomain.com";
    
    mail($email, $subject, $message, $headers);
    $_SESSION['registration_status'] = "请检查邮箱完成激活";
    header("Location: register.php");
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>用户注册</title>
</head>
<body>
    <h2>用户注册</h2>
    <?php if (isset($_SESSION['registration_status'])): ?>
        <div><?= $_SESSION['registration_status']; unset($_SESSION['registration_status']); ?></div>
    <?php endif; ?>
    <form method="post" action="">
        <label>昵称：<input type="text" name="nickname" required></label><br>
        <label>口令：<input type="password" name="password" required></label><br>
        <label>邮箱：<input type="email" name="email" required></label><br>
        <button type="submit">提交注册</button>
    </form>
</body>
</html>